package com.h2psoft.truyen.tranh.activities;

import java.util.ArrayList;

import vn.persoft.extra.customview.CustomToast;
import vn.persoft.extra.internet.Internet;
import android.R.anim;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;

import com.h2psoft.truyen.tranh.R;
import com.h2psoft.truyen.tranh.adapter.AdapterInComicWebView;
import com.h2psoft.truyen.tranh.constants.Constants;
import com.h2psoft.truyen.tranh.dialog.LoadingDialog;
import com.h2psoft.truyen.tranh.objects.ObjChaper;
import com.h2psoft.truyen.tranh.objects.ObjInComic;
import com.h2psoft.truyen.tranh.server.ServerHandling;

public class FragmentNewComic extends Fragment implements OnScrollListener, OnClickListener {
	private String tag = FragmentNewComic.class.getCanonicalName();

	private AdapterInComicWebView adapterInComic;
	private ArrayList<ObjInComic> arrInComics;
	private ArrayList<ObjChaper> temp;
	private ListView lvInComic;
	private Button btnBack, btnNext;
	private LoadingDialog loadingDialog;
	private int start;
	public static int mPrevTotalItemCount;
	private Animation anim, anim2;
	private boolean loadingMore = false;

	public static Fragment newInstance(int start) {
		FragmentNewComic mFragment = new FragmentNewComic();

		Bundle args = new Bundle();
		args.putInt(Constants.KEY_START, start);
		mFragment.setArguments(args);
		return mFragment;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.fragment_new_comic, container, false);
		getExtra();
		firstSetup(v);
		init(v);
		return v;
	}

	private void getExtra() {
		Bundle bundle = getArguments();
		start = bundle.getInt(Constants.KEY_START);
	}

	private void init(View v) {
		lvInComic = (ListView) v.findViewById(R.id.lvlNewComic);
		loadingDialog = new LoadingDialog(getActivity());
		arrInComics = new ArrayList<ObjInComic>();
		adapterInComic = new AdapterInComicWebView(getActivity(), arrInComics);
		lvInComic.setAdapter(adapterInComic);
		loadListChaper();
		lvInComic.setOnScrollListener(this);
	}

	private void firstSetup(View v) {
		btnBack = (Button) v.findViewById(R.id.btnBack_newComic);
		btnNext = (Button) v.findViewById(R.id.btnNext_newComic);
		anim = AnimationUtils.loadAnimation(getActivity(), R.anim.anima_transcale_bottom_invi);
		anim.setFillAfter(true);
		anim.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {

			}

			@Override
			public void onAnimationRepeat(Animation animation) {

			}

			@Override
			public void onAnimationEnd(Animation animation) {
				btnBack.setVisibility(View.GONE);
				btnNext.setVisibility(View.GONE);
			}
		});
		anim2 = AnimationUtils.loadAnimation(getActivity(), R.anim.anima_transcale_bottom_visi);
		anim2.setFillAfter(true);
		btnBack.startAnimation(anim);
		btnNext.startAnimation(anim);
	}

	// Copyright (C) 2011 - 2012 by PERSO STOCK COMPANY.

	private void loadListChaper() {
		if (start == 0)
			lvInComic.setVisibility(View.GONE);
		if (!loadingDialog.isShowing())
			loadingDialog.show();
		if (start % Constants.LOAD_COUNT == 0) {
			btnBack.setVisibility(View.GONE);
			btnNext.setVisibility(View.GONE);
			lvInComic.setVisibility(View.GONE);
			if (Internet.isConnectedInternet(getActivity()))
				new Thread(new Runnable() {
					public void run() {
						synchronized (this) {
							if (!loadingMore) {
								loadingMore = true;
								mPrevTotalItemCount = 0;
								try {
									ServerHandling getListChap = new ServerHandling();
									temp = new ArrayList<ObjChaper>();
									temp.clear();
									getListChap.getNewChaper(temp, start);
								} catch (Exception e) {
									Log.e(tag, e.toString());
								}
								getActivity().runOnUiThread(new Runnable() {
									@Override
									public void run() {
										loadingDialog.dismiss();
										loadingMore = false;
										start += temp.size();
										int tempSize = temp.size();
										for (int i = 0; i < tempSize; i++)
											arrInComics.add(new ObjInComic(temp.get(i).getImgUrl(), temp.get(i).getSecondImgUrl()));
										adapterInComic.notifyDataSetChanged();
										if (temp.size() != 0) {
											lvInComic.setVisibility(View.VISIBLE);
											lvInComic.requestLayout();
										}
									}
								});
							}
						}
					}
				}).start();
			else {
				loadingDialog.dismiss();
				CustomToast.showRandom(getActivity(), R.string.dont_connect_internet);
			}
		}
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		int lastInScreen = firstVisibleItem + visibleItemCount;
		Log.w(tag, "mPrevTotalItemCount" + mPrevTotalItemCount);
		if ((lastInScreen == totalItemCount) && !(loadingMore) && mPrevTotalItemCount > 0) {
			// mPrevTotalItemCount = totalItemCount;
			btnBack.setVisibility(View.VISIBLE);
			btnNext.setVisibility(View.VISIBLE);
			btnBack.startAnimation(anim2);
			btnNext.startAnimation(anim2);
		} else {
			btnBack.startAnimation(anim);
			btnNext.startAnimation(anim);
		}

	}

	@Override
	public void onScrollStateChanged(AbsListView arg0, int arg1) {

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnBack_newComic:
			if (start >= Constants.LOAD_COUNT) {
				start -= Constants.LOAD_COUNT;

			}
			break;

		case R.id.btnNext_newComic:
			break;
		}

	}

}
